<?php
/**
 * Class UserModule
 * 数据表 id username email nickname wechat_id code enable create_time last_time(最后一次登录时间) type
 */
class UserModule extends Data{
    protected $table;

    protected static $selfObjectArray;
    protected function __construct($table) {
        parent::__construct();
        $this->table=!empty($table)&&validateVar($table)?$table:'likyh_user';
        SimpleSession::init();
    }

    /**
     * 初始化函数，并返回当前类
     * @param string $table 表名
     * @return UserModule
     */
    public static function init($table = 'likyh_user'){
        if(!isset(self::$selfObjectArray[$table])){
            self::$selfObjectArray[$table]=new UserModule($table);
        }
        return self::$selfObjectArray[$table];
    }
    //无表时建立通用表
    function install($comment = null){
        $comment=$this->db->quote($comment);
        $sql="CREATE TABLE IF NOT EXISTS `likyh_user` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `username` VARCHAR(255) NULL,
              `email` VARCHAR(255) NULL,
              `nickname` VARCHAR(255) NULL,
              `wechat_id` VARCHAR(255) NULL,
              `code` VARCHAR(255) NULL,
              `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
              `last_time` DATETIME NULL,
              `type` TINYINT(4) DEFAULT 1,
              `enable` TINYINT(4) DEFAULT 1,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT={$comment};";
        $this->db->sqlExec($sql);
        return true;
    }
    public function checkLogin(){
        return isset($_SESSION['putuan'][$this->table]['login'])&&$_SESSION['putuan'][$this->table]['login'];
    }

    /**
     * 用户登录
     * @param $user 注册手机号或者邮箱
     * @param $pass
     * @return DataMessage
     */
    function login($user,$pass){
        $type = $this->checkLoginNameType($user);
        //判断用户名
        if(empty($type)){
            return new DataMessage(DataMessage::STATE_ERROR,'登录失败','登陆账号格式错误');
        }elseif($type == 'email'){
            $user=$this->getUsernameByEmail($user);
        }
        $code=getPassWord($user,$pass);
        $username=$this->db->quote($user);
        $code=$this->db->quote($code);
        $sql="SELECT `id`,`username`,`email`,`nickname`,`wechat_id`, `enable`,
              `create_time`, `last_time`, `type`
              FROM `{$this->table}` WHERE `username`={$username} and `code`={$code}";
        $loginInfo=$this->db->getOne($sql);
        if(!empty($loginInfo)){
            if($loginInfo['enable']){
                $this->updateTime($loginInfo['id']);
                $_SESSION['putuan'][$this->table]['login']=true;
                $_SESSION['putuan'][$this->table]['info']=$loginInfo;
                $this->updateTime($loginInfo['id']);
                return new DataMessage(DataMessage::STATE_SUCCESS,'登录成功');
            }else{
                return new DataMessage(DataMessage::STATE_ERROR,'登录失败','该用户名暂未审核，请联系客服');
            }
        }else{
            return new DataMessage(DataMessage::STATE_ERROR,'登录失败','用户名或密码错误');
        }
    }
    function logout(){
        SimpleSession::release();
    }

    public function getLoginId(){
        return isset($_SESSION['putuan'][$this->table]['info']['id'])?(int)$_SESSION['putuan'][$this->table]['info']['id']:null;
    }
//    function getLoginInfo(){
//        return isset($_SESSION['putuan'][$this->table]['info'])?$_SESSION['putuan'][$this->table]['info']:array();
//    }
    function getLoginInfo(){
        $id=$this->getLoginId();
        return $this->getDetail($id);
    }
    //用邮箱查用户名
    function getUsernameByEmail($email){
        $sql="SELECT `username` FROM `$this->table` WHERE `email`=?";
        return $this->db->getValue($sql,$email);
    }

    /**
     * 判断登陆账号为手机或邮箱
     * @param $loginName
     * @return null|string
     */
    function checkLoginNameType($loginName){
        if($this->checkTelFormatValid($loginName)){
            //手机号
            return 'tel';
        }elseif($this->checkEmailFormatValid($loginName)){
            //邮箱
            return 'email';
        }else{
            return null;
        }
    }
    //检查用重复户名
    public function checkUsername($username){
        $username=$this->db->quote($username);
        $sql="select 1 from `{$this->table}` where `username`=$username";
        return $this->db->getExist($sql);
    }
    //检查手机格式正确否
    function checkTelFormatValid($tel){
        return preg_match('/^1[34578]\d{9}$/',$tel);
    }
    //检查邮箱格式正确否
    function checkEmailFormatValid($email){
        return preg_match('/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/',$email);
    }

    //enable设为0
    public function hidden($user_id){
        $user_id=(int)$user_id;
        $data['enable']=0;
        return $this->db->update($this->table,$user_id,$data,true)==1;
    }

    public function getList($rows=30,$offset=0,$enable=null){
        $rows=(int)$rows;
        $offset=(int)$offset;
        if(empty($enable)){
            $condition='';
        }else{
            $enable=(int)$enable;
            if($enable==1){
                 $condition=" and `enable`=$enable ";
            }else{
                 $condition=" and `enable` != 1 ";
            }
           
        }
        $sql="SELECT SQL_CALC_FOUND_ROWS `id`,`username`,`email`,`nickname`,`wechat_id`,`enable`,
        `create_time`,`last_time`,`type` FROM `{$this->table}` where 1 $condition
        order by `create_time` DESC limit $offset,$rows";
        return $this->db->getList($sql);
    }

    function getListByType($rows=30,$offset=0,$user_type=null){
        $rows=(int)$rows;
        $offset=(int)$offset;
        if(empty($user_type)){
            $condition='';
        }else if($user_type=='service'){
            $condition=" and `type`= ".$this->db->quote($user_type)."or `type`='both'";
        }else if($user_type=='shop'){
            $condition=" and `type`=".$this->db->quote($user_type)."or `type`='both'";
        }
        $sql="SELECT SQL_CALC_FOUND_ROWS `id`,`username`,`email`,`nickname`,`wechat_id`,`enable`,
        `create_time`,`last_time`,`type` FROM `{$this->table}` where 1 $condition
        order by `create_time` DESC limit $offset,$rows";
        return $this->db->getList($sql);
    }

    function getDetail($ids){
        if(empty($ids)) return null;
        $sql="SELECT `id`,`username`,`email`,`nickname`,`wechat_id`,`enable`,`create_time`,
        `last_time`,`type` FROM `{$this->table}` where ".$this->db->getIdCondition($ids,'id');
        $r=$this->db->getAll($sql);
        if($r){
          return is_array($ids) ? $r:$r[0];  
        }    
    }

    //简单注册
    function register($username,$pass){
        if($this->checkUsername($username)) return -1;
        $data['username']=$username;
        $data['code']=getPassWord($username,$pass);
        return $this->db->insert($this->table,$data)==1 ? (int)$this->db->insertId():-1;
    }
    public function modifyPass($username,$old,$new){
        if($old==$new){
            return "新密码不能和旧密码相同";
        }
        $old=getPassWord($username,$old);
        $new=getPassWord($username,$new);
        $username=$this->db->quote($username);
        $old=$this->db->quote($old);
        $sql="SELECT `id` FROM `{$this->table}` WHERE `username`={$username} and `code`={$old}";
        $user_id=(int)$this->db->getValue($sql);
        if(empty($user_id)){
            return "旧密码错误";
        }
        $data['code']=$new;
        $alterPass=$this->db->update($this->table,$user_id,$data);
        return $alterPass?"success":"出现错误了，谁知道发生了什么，重新试试吧";
    }
    function resetPass($username, $pass){
        // 使用请千万注意，要自行确认用户是不是合法修改，不要随意就修改密码！
        // 如果是一般的修改密码，用新旧密码修改(modifyPass)
        $sql="UPDATE `{$this->table}` SET `code`=? WHERE `username`=?";
        $alterPass=$this->db->sqlExec($sql, getPassWord($username,$pass), $username);
        return $alterPass?"success":"出现错误了，谁知道发生了什么，重新试试吧";
    }
    //修改资料
    function modifyInfo($id,$email=null,$nickname=null,$wechat_id=null){
        $id=(int)$id;
        $data['email']=$email;
        $data['nickname']=$nickname;
        $data['wechat_id']=$wechat_id;
        return $this->db->update($this->table,$id,$data) == 1;
    }
    /**
     * 修改最后一次登录时间
     * @param int $user_id
     */
    function updateTime($user_id){
        $user_id=(int)$user_id;
        $data['last_time']=Date('Y-m-d H:i:s',time());
        $this->db->update($this->table,$user_id,$data)==1;
    }
    function getIdByUsername($username){
        $sql="SELECT `id` FROM `{$this->table}` WHERE `username`=?";
        return $this->db->getValue($sql,$username);
    }
    function getType($id){
        $info=$this->getDetail($id);
        return $info['type'];
    }
    //设置用户类型，putuan里面有user(default)|shop|service
    function setType($id,$type){
        $id=(int)$id;
        $data['type']=$type;
        return $this->db->update($this->table,$id,$data) == 1;
    }

    // 生成验证码，remark是一个标记，随便给一个内容就可以，在检查的时候，remark不同就认为不匹配
    function getCode($remark){
        $_SESSION['putuan'][$this->table]['code']=rand(100000, 1000000);
        $_SESSION['putuan'][$this->table]['remark']=$remark;
        $_SESSION['putuan'][$this->table]['time']=10;
        return $_SESSION['putuan'][$this->table]['code'];
    }
    function checkCode($remark, $code){
        if(!isset($_SESSION['putuan'][$this->table]['code'])|| empty($_SESSION['putuan'][$this->table]['code'])){
            return new DataMessage(DataMessage::STATE_WARRING, "验证码尚未发送");
        }
        if($_SESSION['putuan'][$this->table]['time']--<=0){
            return new DataMessage(DataMessage::STATE_WARRING, "验证码验证次数过多，请重新发送");
        }
        if($_SESSION['putuan'][$this->table]['remark']!=$remark){
            return new DataMessage(DataMessage::STATE_WARRING, "手机号码错误，请重新发送");
        }
        return $_SESSION['putuan'][$this->table]['code']==$code?
            new DataMessage(DataMessage::STATE_SUCCESS, '验证码正确'):
            new DataMessage(DataMessage::STATE_ERROR, '验证码错误');
    }
    
       /**
     * 获取余额可用/不可用的用户列表
     */
    function getmoneyuserList($rows=30,$offset=0,$money_usable=null ){
        $rows=(int)$rows;
        $offset=(int)$offset;
        $money_usable=(int)$money_usable;
        switch($money_usable){
            case 1:  $condition=" and `money_usable`=1  " ; break;
            case 0:  $condition=" and `money_usable`=0  " ; break;
            default:$condition=''; break;
        }
//        $sql="SELECT SQL_CALC_FOUND_ROWS `id`,`username`,`email`,`nickname`,`wechat_id`,`enable`,
//        `create_time`,`last_time`,`type` FROM `{$this->table}` where 1 $condition
//        order by `create_time` DESC limit $offset,$rows";
        $sql="select SQL_CALC_FOUND_ROWS a.id, a.username,a.email,`nickname`,`wechat_id`,`enable`, `create_time`,`last_time`,`type`,b.money_usable FROM user a LEFT JOIN user_info b ON  a.id=b.user_id "
        . "WHERE 1 $condition order by `create_time` DESC limit $offset,$rows";
       return $this->db->getList($sql);
    }
} 